package com.haochang.chunkvod.controller.activity.hostess;

import java.util.ArrayList;
import java.util.List;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.controller.fragment.hostess.RoomClearFragment;
import com.haochang.chunkvod.controller.fragment.hostess.RoomManagerFragment;
import com.haochang.chunkvod.controller.fragment.hostess.RoomSettingFragment;
import com.haochang.chunkvod.controller.fragment.hostess.SubcontractFragment;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.view.vod.dialog.ActivityDialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 *         created at 2016/8/24 18:02
 *         房间操作页面
 */
public class RoomManagerActivity extends BaseActivity
{
	private LinearLayout group_function;
	private ImageView cursorIv;// 选项下面的图片
	private BaseTextView tv_room_manager, tv_subcontract, tv_room_setting, tv_room_clear;//选项
	private ViewPager viewPager;//viewpager

	private int offset = 0;//偏移量（手机屏幕宽度 / 选项卡总数 - 选项卡长度） / 2
	private int lineWidth;//下划线图片宽度
	private int current_index = 0;//当前选项卡的位置
	private int oldPosition = 0;//viewPager上一次位置

	private List<BaseTextView> titles = new ArrayList<BaseTextView>();//存储选项的集合
	//选项卡索引
	private static final int TAB_COUNT = 4;
	private static final int TAB_MANAGER = 0;
	private static final int TAB_SUB = 1;
	private static final int TAB_SETTING = 2;
	private static final int TAB_CLEAR = 3;
	//房间状态
	private String roomStatue = "";
	//房号
	private String roomNum = "";
	//房间编号
	private String roomId = "";
	//房间用途
	private String roomUsage = "";
	//账单号
	private String billId = "";
	//房间类型编号
	private String roomTypeId = "";
	//房间类型
	private String roomType = "";

	private List<BaseFragment> listFragment = new ArrayList<BaseFragment>();//viewPager中显示界面的集合
	private RoomManagerFragment roomManagerFragment;//房间管理
	private SubcontractFragment subcontractFragment;//转包
	private RoomSettingFragment roomSettingFragment;//房间设置
	private RoomClearFragment roomClearFragment;//清洁维修

	private String expectedTime;//服务器返回的最新时间
	private ArrayList<DialogItemInfo> listRoomTypes;//房型list
	private ArrayList<DialogItemInfo> listUsage;//房间用途list
	private ArrayList<ActivityDialogItemInfo> listActivity;//活动list
	private ArrayList<DialogItemInfo> listRoomPolicies;//房间计费策略list
	private String relateCode;// 房间连接码
	private String customer_count;// 房间默认人数

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		roomNum = getIntent().getStringExtra(IntentKey.ROOM_NUM);
		roomStatue = getIntent().getStringExtra(IntentKey.ROOM_STATUS);
		roomId = getIntent().getStringExtra(IntentKey.ROOM_ID);
		roomUsage = getIntent().getStringExtra(IntentKey.ROOM_USAGE);
		billId = getIntent().getStringExtra(IntentKey.BILL_ID);
		roomTypeId = getIntent().getStringExtra(IntentKey.ROOM_TYPE_ID);
		roomType = getIntent().getStringExtra(IntentKey.ROOM_TYPE);
		Logger.e("roomNum:" + roomNum + "  roomStatue:" + roomStatue + "  roomStatue:" + roomUsage + "  roomUsage:" + billId + "  roomStatue:" + billId
				+ "  roomTypeId:" + roomTypeId + "  roomType:" + roomType);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_room_manager);
		group_function = (LinearLayout) findViewById(R.id.group_function);
		group_function.setVisibility(View.GONE);
		initTitle();
		requestRoomInfo();
	}

	/**
	 * 获取房间操作基本信息
	 */
	private void requestRoomInfo()
	{
		new HostessData(this).requestRoomInfo(roomId, roomTypeId, new HostessData.HostessRoomInfoListener()
		{
			@Override
			public void onRequestSuccess(ArrayList<DialogItemInfo> usageList1, ArrayList<ActivityDialogItemInfo> activityList1, String expectedTime1,
					ArrayList<DialogItemInfo> roomPolicies1, ArrayList<DialogItemInfo> roomTypes1, String relateCode1, String customer_count)
			{
				listRoomTypes = roomTypes1;
				expectedTime = expectedTime1;
				relateCode = relateCode1;
				listUsage = usageList1;
				listActivity = activityList1;
				listRoomPolicies = roomPolicies1;
				RoomManagerActivity.this.customer_count = customer_count;
				group_function.setVisibility(View.VISIBLE);

				initUI();
				initFragment();
				initTitlesAndViewsByStatue();
				initImageView();
				initViewPager();
			}

			@Override
			public void onFail(int errorNo, String msg)
			{
			}

		});
	}

	/**
	 * 初始化布局和监听
	 */
	private void initUI()
	{
		viewPager = (ViewPager) findViewById(R.id.vPager);
		cursorIv = (ImageView) findViewById(R.id.iv_tab_bottom_img);
		tv_room_manager = (BaseTextView) findViewById(R.id.tv_room_manager);
		tv_room_manager.setTag(TAB_MANAGER);
		tv_subcontract = (BaseTextView) findViewById(R.id.tv_subcontract);
		tv_subcontract.setTag(TAB_SUB);
		tv_room_setting = (BaseTextView) findViewById(R.id.tv_room_setting);
		tv_room_setting.setTag(TAB_SETTING);
		tv_room_clear = (BaseTextView) findViewById(R.id.tv_room_clear);
		tv_room_clear.setTag(TAB_CLEAR);
		tv_room_manager.setOnClickListener(onBarBaseClickListener);
		tv_subcontract.setOnClickListener(onBarBaseClickListener);
		tv_room_setting.setOnClickListener(onBarBaseClickListener);
		tv_room_clear.setOnClickListener(onBarBaseClickListener);
	}

	/**
	 * 初始化标题栏
	 */
	private void initTitle()
	{
		TitleView titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(roomNum).setRightIconVISIBLE(false).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{

			}

		});
	}

	/**
	 * 初始化Fragment
	 */
	private void initFragment()
	{
		roomManagerFragment = new RoomManagerFragment();
		subcontractFragment = new SubcontractFragment();
		roomSettingFragment = new RoomSettingFragment();
		roomClearFragment = new RoomClearFragment();
		Bundle bundle = new Bundle();
		bundle.putString(IntentKey.ROOM_DEFAULT_COUNT, customer_count);//房间设置的人数
		bundle.putString(IntentKey.ROOM_ID, roomId);//房间id
		bundle.putString(IntentKey.ROOM_STATUS, roomStatue);//房间状态
		bundle.putString(IntentKey.BILL_ID, billId);//账单id
		bundle.putString(IntentKey.ROOM_TYPE_ID, roomTypeId);//房型id
		bundle.putString(IntentKey.ROOM_TYPE, roomType);//当前房型
		bundle.putString(IntentKey.ROOM_USAGE, roomUsage);//当前房间用途
		bundle.putString(IntentKey.EXP_TIME, expectedTime);//预结时间
		bundle.putString(IntentKey.RELATE_CODE, relateCode);//房间码
		bundle.putParcelableArrayList(IntentKey.ROOM_TYPES, listRoomTypes);//计费房间类型list
		bundle.putParcelableArrayList(IntentKey.USAGE_LIST, listUsage);//房间用途list
		bundle.putParcelableArrayList(IntentKey.ACTIVITY_LIST, listActivity);//当前房间活动
		bundle.putParcelableArrayList(IntentKey.ROOM_POLICIES, listRoomPolicies);//房间计费策略
		bundle.putString(IntentKey.COMSTMER_COUNT, getIntent().getStringExtra(IntentKey.COMSTMER_COUNT));
		bundle.putString(IntentKey.REMARKS, getIntent().getStringExtra(IntentKey.REMARKS));
		roomManagerFragment.setArguments(bundle);
		subcontractFragment.setArguments(bundle);
		roomSettingFragment.setArguments(bundle);
		roomClearFragment.setArguments(bundle);
	}

	/**
	 * 初始化底部下划线
	 */
	private void initImageView()
	{
		// 获取图片宽度
		lineWidth = BitmapFactory.decodeResource(getResources(), R.drawable.ic_tab).getWidth();
		// 用于获取屏幕分辨率
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		// 获取分辨率宽度
		offset = (screenW / TAB_COUNT - lineWidth) / 2;
		int start_index = Integer.parseInt(titles.get(0).getTag().toString());
		current_index = start_index;
		int marginLeft = start_index * (offset * 2 + lineWidth) + offset;

		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) cursorIv.getLayoutParams();
		params.setMargins(marginLeft, 0, 0, 0);
		cursorIv.setLayoutParams(params);
		if (titles.size() > 0)
			titles.get(oldPosition).setTextColor(Color.RED);
	}

	/**
	 * 初始化ViewPager并添加监听事件
	 */
	private void initViewPager()
	{
		if (listFragment != null)
		{
			viewPager.setAdapter(new RoomManagerFragmentPagerAdapter(this.getSupportFragmentManager(), listFragment));
			viewPager.setCurrentItem(oldPosition);
			viewPager.setOffscreenPageLimit(titles.size());
			viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
			{
				int quarterWidth = offset * 2 + lineWidth;//1/4屏幕宽度

				@Override
				public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
				{

				}

				@Override
				public void onPageSelected(int position)
				{
					// 下划线开始移动前的位置
					float fromX = quarterWidth * current_index + offset;
					// 下划线移动完毕后的位置
					BaseTextView toText = titles.get(position);
					int toIndex = Integer.parseInt(toText.getTag().toString()) - Integer.parseInt(titles.get(0).getTag().toString());
					int toX = quarterWidth * toIndex;
					Animation animation = new TranslateAnimation(fromX, toX, 0, 0);
					animation.setFillAfter(true);
					animation.setDuration(100);
					// 给图片添加动画
					cursorIv.startAnimation(animation);
					// 当前Tab的字体变成红色
					if (titles != null && titles.size() > position && titles.size() > oldPosition)
					{
						titles.get(position).setTextColor(Color.RED);
						titles.get(oldPosition).setTextColor(Color.BLACK);
					}
					current_index = Integer.parseInt(toText.getTag().toString());
					oldPosition = position;
				}

				@Override
				public void onPageScrollStateChanged(int state)
				{

				}
			});
		}
	}

	/**
	 * 根据房间状态设置可选中的选项卡
	 */
	private void initTitlesAndViewsByStatue()
	{
		if (!TextUtils.isEmpty(roomStatue))
		{
			if (titles == null)
			{
				titles = new ArrayList<BaseTextView>();
			}
			if (listFragment == null)
			{
				listFragment = new ArrayList<BaseFragment>();
			}
			titles.clear();
			listFragment.clear();
			if (TextUtils.equals("guiding", roomStatue) || TextUtils.equals("using", roomStatue) || TextUtils.equals("prepay", roomStatue))
			{//带客，使用，准备时，（房间管理，转包，房间设置  可操作）
				titles.add(tv_room_manager);
				titles.add(tv_subcontract);
				titles.add(tv_room_setting);
				listFragment.add(roomManagerFragment);
				listFragment.add(subcontractFragment);
				listFragment.add(roomSettingFragment);
			} else if ("empty".equals(roomStatue))
			{//空房 （房间管理，清洁 可操作）
				titles.add(tv_room_manager);
				titles.add(tv_room_clear);
				listFragment.add(roomManagerFragment);
				listFragment.add(roomClearFragment);
			} else if ("purifying".equals(roomStatue) || "repairing".equals(roomStatue))
			{//清洁维修 （清洁 可操作）
				titles.add(tv_room_clear);
				listFragment.add(roomClearFragment);
			} else
			{//只用房间管理可操作）
				titles.add(tv_room_manager);
				listFragment.add(roomManagerFragment);
			}
		}
	}

	private OnBaseClickListener onBarBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			int len = titles.size();
			for (int i = 0; i < len; i++)
			{
				if (Integer.parseInt(v.getTag().toString()) == Integer.parseInt(titles.get(i).getTag() + ""))
				{//点击的tag与第i个tag一样
					viewPager.setCurrentItem(i);
					return;
				}
			}
		}
	};

	/**
	 * ViewPager适配器
	 */
	public class RoomManagerFragmentPagerAdapter extends FragmentPagerAdapter
	{

		List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();

		public RoomManagerFragmentPagerAdapter(FragmentManager fm, List<BaseFragment> fragmentList)
		{
			super(fm);
			this.fragmentList = fragmentList;
		}

		@Override
		public Fragment getItem(int position)
		{
			return null == fragmentList ? null : fragmentList.get(position);
		}

		@Override
		public int getCount()
		{
			return fragmentList == null ? 0 : fragmentList.size();
		}

	}

}
